<template>
  <!-- 将doc文件转ofd,上传去盖章 -->
  <div style="width:100%">
    <el-button type="primary" @click="switchOfd" :disabled="!mixEditable">
      盖章
    </el-button>
  </div>
</template>
<script>
import { AjaxUtil } from "base/lib";
import routerContextPath from '../../mixins/router-context-path.js'
export default {
  name:'stamp',
  mixins: [ routerContextPath],
  props:{
    value:'',
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    headers: {
      default: () => {},
    },
    isInChildren: {
      type: Boolean,
      default: false
    },
    fileId: {
      type: String,
      default: ''
    },
    fileName: {
      type: String,
      default: ''
    }
  },
  computed: {
    isDesigner(){
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
    dispatchProxy(){
      if (Vue.prototype.dispatchProxy) {
        return Vue.prototype.dispatchProxy(this)
      } else {
        return this.dispatch
      }
    },
  },
  data() {
    return {
      downloadUrl: '',
      interval: null,
      fileKey: '',
      flowId: '',
    }
  },
  watch: {
  },
  created(){
    
  },
  methods: {
    async switchOfd() {
      console.log(this.fileName.slice(this.fileName.lastIndexOf('.')))
      if (['.pdf', '.ofd'].includes(this.fileName.slice(this.fileName.lastIndexOf('.')))) {
        this.getOfdFile({fileId: this.fileId, fileName: this.fileName})
        return
      }
      // const prefix = 'http://121.36.242.165:28090'
      const prefix = window.location.origin
      let params = new FormData()
      params.append('taskId',  String(Math.random()*100000000).slice(0,7))
      params.append('docFilename', this.fileName)
      params.append('docUrl', `${prefix}${this.contextPath}/XFfileServer/fileDownload?id=${this.fileId}`)
      params.append('target', 'ofd')
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.convertFile, params)
      const { msg, data, code } = resp.data
      if (code === 200) {
        await this.downloadFormat(data)
      } else {
        this.$message.error(msg || '转ofd格式失败')
      }
    },
    async downloadFormat(item) {
      const { downloadId, routerKey } = item
      const user = localStorage.getItem('user')
      const data = {
        downloadId,
        routeKey: routerKey,
        userName: JSON.parse(user).userName,
        target: 'ofd',
        fileName: this.fileName.slice(0, this.fileName.lastIndexOf('.'))
      }
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.operateDocumentResultDownload, data)
      if (!resp.error) {
        this.getOfdFile(resp.data)
      }
    },

    // 获取文件流，上传
    async getOfdFile({fileId, fileName}) {
      AjaxUtil.ajax({
        responseType : 'blob',
        // url: window.location.origin + `/XFfileServer/fileDownload?id=${fileId}`,
        url: `/XFfileServer/fileDownload?id=${fileId}`,
        method: 'GET',
        data: {},
      }).then(resp => {
        this.uploadFile({file: new File([resp.data], fileName, { type: 'application/ofd' })})
      })
    },
    async previewFile() {
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WXQController.sealPlatformFilePreview, {
        flowId: this.flowId,
        fileKeys: [
          {
            fileKey: this.fileKey
          }
        ],
        signProviderId: '123'
      })
      const { code, data } = resp.data
      // if (code === 200) {
        return data
      // }
    },
    async uploadFile({file}){
      let params=new FormData()
      params.append('file',file)
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WXQController.sealPlatformUpload, params)
      if (!resp.error && resp.data) {
        const { fileKey } = resp.data.data[0]
        this.fileKey = fileKey
        this.providerFlow(fileKey)
      }
    },
    async providerFlow(fileKey) {
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WXQController.providerFlow, {
        // "redirectUrl": "",
        "callbackUrl": "www.esign.cn/callback",
        "subject": "测试流程",
        "signProviderId": "123",
        "docs": [
            {
                "docFilekey": fileKey,
                "docName": "test.pdf",
                "docPwd": "123"
            }
        ],
        "signers": [
            {
                "name": "赵志考",
                "mobile": "13483118409",
                "uscc": "911101087601303428",
                "orgName": "北京点聚信息技术有限公司",
                "signFiles": [
                    {
                        "docFilekey": fileKey,
                        "signPos": [
                            {
                                "signType": 0,
                                "sealType": "01",
                                "posX": 100,
                                "posY": 100,
                                "posPage": "1"
                            }
                        ]
                    }
                ],
                "order": 1
            }
        ]
      })
      if (!resp.error && resp.data) {
        console.log(resp,'===resp')
        const { message, success} = resp.data
        if (!success) {
          this.$message.error(message)
        } else {
          const { flowId, signTasks } = resp.data.data
          this.flowId = flowId
          this.getDeatil(flowId)
          if (signTasks && signTasks[0]) {
            window.open(signTasks[0].signUrl)
          }
        }
      }
    },
    // 查询签署详情
    async getDeatil(flowId) {
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WXQController.openFlow, {flowId})
      const { status, flowStatus, finishFileKey } = resp.data.data
      if (flowStatus === '完成' && finishFileKey && JSON.parse(finishFileKey).some(i => i.fileKey === this.fileKey)) {
        const downloadUrl = await this.getDownloadUrl()
        this.getFinalFile(downloadUrl)
      } else {
        if (this.interval) {
          clearTimeout(this.interval)
        }
        this.interval = setTimeout(() => this.getDeatil(flowId), 1000)
      }
    },
    // 获取盖章文件id
    async getFinalFile(url) {
      const user = localStorage.getItem('user')
      const fileName = this.fileName.split('.')[0] + '.ofd'
      const userName = JSON.parse(user).userName
      AjaxUtil.ajax({
        url: `/XFfileServer/remoteFileUpload?rmoteUrl=${encodeURIComponent(url)}&fileName=${fileName}&userName=${userName}`,
        method: 'GET',
        data: {},
      }).then(resp => {
        const obj = resp.data[0]
        this.$emit('input', obj.id)
        this.$emit('stampOver', obj)
      })
    },
    async getDownloadUrl() {
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WXQController.sealPlatformDownloadUrl, {fileKey: this.fileKey})
      const { code, data } = resp.data
      if (code === 200) {
        return data.downloadUrl
      }
    },
    error(err, file, fileList) {
      this.$emit('uploadError',{err, file, fileList})
    },
    success(response, file, fileList) {

    },
  }
}
</script>
<style lang="scss" scoped>
  .wps_container {
    display: flex;
    .left {
      flex: 1;
    }
    .el-button {
      margin-left: 5px;
    }
  }
  a {
    text-decoration: none;
    color: #fff;
  }
  a:link {
    color: #fff;
  }
  a:hover {
    color: #fff;
  }
</style>